import Vue from 'vue'
import Vuex from 'vuex'
import Storage from 'vue-ls'
Vue.use(Vuex)
let rec = null;
let seq = 0;
import {
	sendWx
} from '@/api/index'
const websockStore = {
	state: {
		websock: null,
		eventlist: [],
		sdTestQuestId: '', //发题id
		tempsdTestQuestId: "", //临时题发题id
		deviceType: localStorage.getItem('machType'), //接收器设备状态
		conncted: false,
		machId: '',
		studentList: [],
		isAnswering: localStorage.getItem('isAnswering'), //是否正在答题中
		stopDeviceEventList: [], //需要关闭的指令列表
		whiteList: sessionStorage.getItem('whiteList') ? JSON.parse(sessionStorage.getItem('whiteList')) : [], //白名单
		sendTopicData: sessionStorage.getItem('sendTopicData') ? JSON.parse(sessionStorage.getItem(
			'sendTopicData')) : {}, //已发试题数据
	},
	mutations: {
		WEBSOCKET_INIT(state, url) {
			let that = this;
			console.log(JSON.stringify(url))

			if (state.conncted) {
				return
			}
			console.log('开始连接', new Date().getTime())
			state.websock = new WebSocket(url);
			state.websock.onopen = function() {
				console.log("连接成功！", state.deviceType, new Date().getTime());
				state.conncted = true;
				//如果是有线
				if (state.deviceType == 'wired') {
					heartCheck.reset().start();
					/* 如果是有线，需要获取设备是否在线 */
					seq++;
					that.commit('WEBSOCKET_SEND', {
						fun: 'get_hw_dev_s',
						seq: seq
					});
				} else {
					heartCheck.reset()
				}
			}

			state.websock.onmessage = (callBack) => {
				// console.log("ws接收！");
				//console.log("ws接收"+callBack.data);
				//如果是有线
				if (state.deviceType == 'wired') {
					heartCheck.reset().start(); //收到任何信息，都重置心跳检查
				}
				let data = callBack.data;
				if (data == '连接成功') {
					return false
				}
				try {
					data = JSON.parse(callBack.data)
				} catch (e) {
					//TODO handle the exception
				}
				if (data.fun != 'heart_update') {
					console.log("ws接收" + JSON.stringify(data));
				}

				let method = '';
				if (state.deviceType == 'wired') {
					switch (data.fun) {
						case 'get_hw_dev_s': {
							/* 获取设备链接状态 */
							if (data.result == 0) {
								data.msg = "没有插入设备哦";
								method = 'toast';
							} else if (data.result == 1) {
								//设备链接成功
								that.commit('WEBSOCKET_SEND', {
									fun: 'get_dev_info'
								});
							} else {
								data.msg = '同时插入了' + data.result + '设备哦';
								method = 'toast';
							}
							break
						}
						/* 返回设备信息 */
						case 'get_wl_list': {
							if (data.dev_sn) {
								state.machId = data.dev_sn;
								method = 'getDeviceInfo';
							}
							break
						}
						/* 监听usb接口链接状态 */
						case 'jsq_pnp_event': {
							let msg = {
								machineId: state.machId,
								val: data.event == 'disconnected' ? 0 : 1
							}
							data = msg;
							method = 'online';

							break
						}
						/*读卡 */
						case 'read_card_start': {
							method = 'read_card_start';
							break
						}
						/* 刷卡上报 */
						case 'card_update': {
							method = 'card_update';
							break
						}

						/* 返回绑卡信息 */
						case 'update_wireless_card': {
							method = 'update_wireless_card';
							break
						}
						// 绑定姓名成功后的回显
						case 'name_update': {
							method = 'name_update';
							break
						}
						//552G 自动绑卡返回
						case 'update_dtq_status': {
							method = 'update_dtq_status';
							break
						}
						/* 返回答题信息 */
						case 'answer_update': {
							method = 'wiredanswer';
							break
						}
						/*  课后作业发送成功*/
						case 'homework_start': {
							data.msg = '课后作业发送成功';
							data.msgtype = "success";
							method = 'toast';
							break
						}
						/* 返回课后作业答题信息 */
						case 'homework_update': {
							method = 'wiredanswer';
							break
						}
						/* 返回课后作业答题信息 */
						case 'homework_confirm': {
							method = 'toastReceiveUser';
							break
						}
						//举手
						case 'raise_hand_update': {
							method = 'raise_hand_update';
							break
						}
						//签到
						case 'sign_in_update': {
							method = 'sign_in_update';
							break
						}

					}

				} else {
					switch (data.type) {
						//开始答题
						case 'answer': {
							if (data.wsSchTempAnswerRecDtos && data.wsSchTempAnswerRecDtos.length > 0) {
								method = 'tempAnswer';
							}
							if (data.wsSchAnswerRecDtos && data.wsSchAnswerRecDtos.length > 0) {
								method = 'answer';
							}
							//method = data.urlPaths[0].method;
							break
						}
						//结束答题
						case 'over': {
							method = 'over';
							break
						}
						//更新学生
						case 'cardstate': {
							method = 'updateStudent';
							break
						}
						//刷卡
						case 'bindcard': {
							method = 'bindcard';
							break
						}
						case 'online': {
							method = 'online';
						}
						//绑定学生成功
						case 'bindSendSuccess': {
							method = 'bindSendSuccess';
						}
						//更新课后作业
						case 'homeWork': {
							method = 'homeWork';
						}

					}

				}
				//如果是设备升级
				switch (data.type) {
					//开始答题
					case 'prog': {
						method = 'prog';
						break
					} //开始答题
					case 'upgradeResult': {
						method = 'upgradeResult';
						break
					}
				}
				if (method) {
					state.eventlist.push({
						method,
						data: data
					})
				}
				// console.log('zhelihahaha ', state.eventlist, data)
			}
			state.websock.onerror = function(e) { //错误
				console.log("ws错误！", e);
				state.conncted = false;
				if (state.deviceType == 'wired') {
					/* 重连 */
					state.eventlist.push({
						method: 'sdkoffline',
						data: {
							code: 1006,
							msg: 'SDK断开了，请手动重启'
						}
					})
				}


			}
			state.websock.onclose = function(e) { //关闭
				console.log("ws关闭！", new Date().getTime());
				console.log(e);
				state.conncted = false;
				//如果是意外关闭，触发重连
				if (state.deviceType == 'wired') {
					/* 重连 */
					state.eventlist.push({
						method: 'sdkoffline',
						data: {
							code: e.code,
							msg: 'SDK断开了，请手动重启'
						}
					})
				}


			}

		},
		WEBSOCKET_SEND(state, message) {
			console.log("ws发送信息！", message, state.conncted);
			state.conncted && state.websock.send(JSON.stringify(message) + "\n");
			//state.websock.send(JSON.stringify(message) + "\n");
		},
		WEBSOCKET_CLOSE(state) {
			state.websock.close(); //离开路由之后断开websocket连接
			//清空重连逻辑
			console.log('开始主动关闭')
			state.machId = "";
			rec && clearTimeout(rec);
		},
		WEBSOCKET_RECONNECT(state, url) {
			if (state.conncted) return;
			rec && clearTimeout(rec);
			// 延迟5秒重连  避免过多次过频繁请求重连
			rec = setTimeout(() => {
				console.log('开始重新链接')
				this.commit('WEBSOCKET_INIT', url);
			}, 5000);
		},
		//发题id
		SET_sdTestQuestId(state, id) {
			state.sdTestQuestId = id;
			localStorage.setItem('sdTestQuestId', id);
		},
		//临时题发题id
		SET_tempsdTestQuestId(state, id) {
			state.tempsdTestQuestId = id;
			localStorage.setItem('tempsdTestQuestId', id);
		},
		//接收器类型
		SET_deviceType(state, deviceType) {
			state.deviceType = deviceType;
			localStorage.setItem('machType', deviceType);
		},
		//学生名单
		SET_studentList(state, studentList) {
			state.studentList = studentList;
		},
		//是否正在答题
		SET_isAnswering(state, isAnswering) {
			state.isAnswering = isAnswering;
			localStorage.setItem('isAnswering', isAnswering);
		},
		CLEAR_EVENTLIST(state) {
			state.eventlist = []
		},
		SET_STOPDEVICEEVENTLIST(state, list) {
			state.stopDeviceEventList = [...list];
		},
		SET_WHITELIST(state, list) {
			state.whiteList = [...list];
			sessionStorage.setItem('whiteList', JSON.stringify(list))
		},
		SET_sendTopicData(state, sendTopicData) {
			state.sendTopicData = {
				...sendTopicData
			};
			sessionStorage.setItem('sendTopicData', JSON.stringify(sendTopicData))
		}
	},
	actions: {
		WEBSOCKET_INIT({
			commit
		}, url) {
			try {
				commit('WEBSOCKET_INIT', url)

			} catch (e) {
				commit('WEBSOCKET_RECONNECT', url)
			}

		},
		WEBSOCKET_SEND({
			commit
		}, p) {
			p.type = 3;
			commit('WEBSOCKET_SEND', p)
		},
		WEBSOCKET_CLOSE({
			commit
		}) {
			commit('WEBSOCKET_CLOSE')
		}
	}
}
export default websockStore
// 判断字符是否为汉字，
function isChinese(s) {
	return /[\u4e00-\u9fa5]/.test(s);
}
// 把字符串中的汉字转换成Unicode
function ch2Unicdoe(str) {
	if (!str) {
		return;
	}
	var unicode = '';
	for (var i = 0; i < str.length; i++) {
		var temp = str.charAt(i);
		if (isChinese(temp)) {
			unicode += '\\u' + temp.charCodeAt(0).toString(16);
		} else {
			unicode += temp;
		}
	}
	return unicode;
}

//心跳检测
var heartCheck = {
	timeout: 1 * 60 * 1000,
	serverTimeoutObj: null,
	reset: function() {
		clearTimeout(this.serverTimeoutObj);
		return this;
	},
	start: function() {
		var self = this;
		self.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置，说明后端主动断开了
			websockStore.state.websock.close();
			console.log('心跳没有了')
		}, self.timeout)
	}
}